package main

import (
	"errors"
	"fmt"
	"log"
	"net"
	"time"
)

func handleConnection(conn net.Conn) {
	defer func() { _ = conn.Close() }()

	buffer := make([]byte, 4)
	for {
		// 设置读取超时
		_ = conn.SetReadDeadline(time.Now().Add(30 * time.Second))

		// 读取客户端数据
		n, err := conn.Read(buffer)
		if err != nil {
			var netErr net.Error
			if errors.As(err, &netErr) && netErr.Timeout() {
				fmt.Printf("读取超时，关闭连接\n")
			} else {
				fmt.Printf("客户端 %s 断开连接\n", conn.RemoteAddr().String())
			}
			return
		}

		// 检查是否是退出信号
		if string(buffer[:n]) == "quit" {
			fmt.Printf("客户端 %s 请求断开连接\n", conn.RemoteAddr().String())
			return
		}

		// 设置写入超时
		_ = conn.SetWriteDeadline(time.Now().Add(*timeout))

		// 发送响应
		_, err = conn.Write([]byte("Pong"))
		if err != nil {
			fmt.Printf("发送响应失败（%s）: %v\n", conn.RemoteAddr().String(), err)
			return
		}
	}
}

func startServer() {
	listener, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("启动服务器失败: %v\n", err)
		return
	}
	defer func() { _ = listener.Close() }()

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Printf("接受连接失败: %v\n", err)
			continue
		}

		fmt.Printf("新客户端连接: %s\n", conn.RemoteAddr().String())
		go handleConnection(conn)
	}
}
